//
//  TabFourViewController.m
//  DaJiang
//
//  Created by sally on 16/9/24.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "BecomeExpertViewController.h"
#import "CacheManager.h"
#import "CheckStatusViewController.h"
#import "ExpertBeFreeViewController.h"
#import "ExpertCenterViewController.h"
#import "HelpViewController.h"
#import "LoginViewController.h"
#import "MyCollectViewController.h"
#import "OrderListViewController.h"
#import "SetPswViewController.h"
#import "TabFourViewController.h"
#import "UserDetailViewController.h"
#import "ExpertCell.h"

#define TextExpertCenter @"专家中心"
#define TextOrderMe @"约我的人"
#define TextExpertBeFree @"专家有空"
#define TextOrderExpert @"我约的专家"
#define TextMyCollect @"我的心愿单"
#define TextBecomeExpert @"成为专家"
#define TextHelp @"帮助"
#define TextSet @"设置密码"
#define TextExit @"退出登录"

@interface TabFourViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *tableData;
@property (strong, nonatomic) NSMutableArray *imageData;

@end

@implementation TabFourViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  [self initControl];
}

- (void)viewWillAppear:(BOOL)animated {
  [self initData];
  
  //从订单详情退到订单列表，导航栏强制变白
  [[CommonMethod sharedCommonMethod] setNavAndStatusBar:self.navigationController.navigationBar style:NavStyle_Normal];
}

#pragma mark 初始化控件
- (void)initControl {
  self.title = @"我的管理";
  [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
}

#pragma mark 初始化数据
- (void)initData {
  //设定用户类型
  UserModel *user = [[CacheManager shareInstance] getLastLoginAccount];
  if (user) {                         //已登录
    if (user.user_data.is_pro == 1) { //专家
      self.mimeType = MimeType_Expert;
    } else { //普通
      self.mimeType = MimeType_Normal;
    }
  } else { //未登录
    self.mimeType = MimeType_Not_Login;
  }
  
  self.tableData = [NSMutableArray array];
  self.imageData = [NSMutableArray array];
  
  if (self.mimeType == MimeType_Expert) {
    [self.tableData addObject:@[ user.user_data.user_name ]];
    [self.tableData addObject:@[ TextExpertCenter, TextOrderMe, TextExpertBeFree ]];
    [self.tableData addObject:@[ TextOrderExpert, TextMyCollect ]];
    [self.tableData addObject:@[ TextHelp ]];
    [self.tableData addObject:@[ TextSet, TextExit ]];
    
    [self.imageData addObject:@[ @"ic_default" ]];
    [self.imageData addObject:@[ @"me_expert_center_ic", @"me_order_expert_ic", @"me_expert_be_free_ic" ]];
    [self.imageData addObject:@[ @"me_order_expert_ic", @"me_collect_ic" ]];
    [self.imageData addObject:@[ @"me_help_ic" ]];
    [self.imageData addObject:@[ @"me_set_ic", @"me_exit_ic" ]];
    
  } else {
    [self.imageData addObject:@[ @"ic_default" ]];
    [self.imageData addObject:@[ @"me_order_expert_ic", @"me_collect_ic", @"me_become_expert_ic" ]];
    [self.imageData addObject:@[ @"me_help_ic" ]];
    
    if (self.mimeType == MimeType_Not_Login) {
      [self.tableData addObject:@[ @"立即登录" ]];
      [self.tableData addObject:@[ TextOrderExpert, TextMyCollect, TextBecomeExpert ]];
      [self.tableData addObject:@[ TextHelp ]];
      [self.tableData addObject:@[ TextSet ]];
      [self.imageData addObject:@[ @"me_set_ic" ]];
      
    } else {
      [self.tableData addObject:@[ user.user_data.user_name ]];
      [self.tableData addObject:@[ TextOrderExpert, TextMyCollect, TextBecomeExpert ]];
      [self.tableData addObject:@[ TextHelp ]];
      [self.tableData addObject:@[ TextSet, TextExit ]];
      [self.imageData addObject:@[ @"me_set_ic", @"me_exit_ic" ]];
    }
  }
  [self.tableView reloadData];
}

#pragma mark - TableView data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return self.tableData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  return [[self.tableData objectAtIndex:section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
  return 0.1; //section头部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
  return GNormalMargin; //section底部高度
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  if (indexPath.section == 0) { //第一项
    return GMineHeadCellHeight;
  }
  return NavHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
  if (indexPath.section == 0) { //第一项
    ExpertCell *expertCell = (ExpertCell *) [tableView dequeueReusableCellWithIdentifier:@"ExpertCell"];
    if (!expertCell) {
      expertCell = [[[NSBundle mainBundle] loadNibNamed:@"ExpertCell" owner:nil options:nil] lastObject];
    }
    
    UserModel *user = [[CacheManager shareInstance] getLastLoginAccount];
    expertCell.expertCellType = ExpertCellType_Mine;
    expertCell.cellData = user;
    expertCell.name2Label.text = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    return expertCell;
    
  } else {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    
    //图标
    cell.imageView.image = [UIImage imageNamed:[[self.imageData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
    
    //主标题
    cell.textLabel.font = GCustomNormalFont;
    cell.textLabel.textColor = GBlackColor;
    cell.textLabel.text = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    //右箭头
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
  }
  
}

#pragma mark TableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [tableView deselectRowAtIndexPath:indexPath animated:YES]; //返回后选中状态消失
  if (![OperationManager gotoLogin]) {
    return;
  }
  
  if (indexPath.section == 0) { //个人资料
    if (self.mimeType == MimeType_Not_Login) {
      LoginViewController *vc = [[LoginViewController alloc] init];
      vc.hidesBottomBarWhenPushed = YES;
      vc.accountType = AccountType_Login;
      [self presentViewController:vc animated:YES completion:nil];
    } else {
      UserDetailViewController *vc = [[UserDetailViewController alloc] init];
      vc.userType = self.mimeType == MimeType_Expert ? UserDetailType_Expert:UserDetailType_Normal;
      vc.userModel = [[CacheManager shareInstance] getLastLoginAccount];
      vc.hidesBottomBarWhenPushed = YES;
      [self.navigationController pushViewController:vc animated:YES];
    }
  }
  
  NSString *title = [[self.tableData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
  if ([title isEqualToString:TextHelp]) { //帮助
    HelpViewController *vc = [[HelpViewController alloc] init];
    vc.helpType = HelpType_Main;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  } else if ([title isEqualToString:TextSet]) { //设置密码
    SetPswViewController *vc = [[SetPswViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  } else if ([title isEqualToString:TextExit]) { //退出
    [self exit];
  } else if ([title isEqualToString:TextExpertCenter]) { //专家中心
    ExpertCenterViewController *vc = [[ExpertCenterViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  } else if ([title isEqualToString:TextOrderMe]) { //约我的人
    OrderListViewController *vc = [[OrderListViewController alloc] init];
    vc.orderType = OrderType_OrderMe;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  } else if ([title isEqualToString:TextExpertBeFree]) { //专家有空
    ExpertBeFreeViewController *vc = [[ExpertBeFreeViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  } else if ([title isEqualToString:TextOrderExpert]) { //我约的专家
    OrderListViewController *vc = [[OrderListViewController alloc] init];
    vc.orderType = OrderType_OrderExpert;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  } else if ([title isEqualToString:TextMyCollect]) { //我的心愿单
    MyCollectViewController *vc = [[MyCollectViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
  } else if ([title isEqualToString:TextBecomeExpert]) { //成为专家
    //判断是否申请成为专家：如果有，则进入审核状态页（不同状态）。否则，进入成为专家页
    [self judgeApplyStatus];
  }
}

//退出
- (void)exit{
  [UIAlertView showWithTitle:nil message:@"确认是否退出？" cancelButtonTitle:@"否" otherButtonTitles:@[ @"是" ] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
    if (buttonIndex == 1) {
      MBProgressHUD *hud = [[CommonMethod sharedCommonMethod] createProgressHUDInView:self.view withMessage:@""];
      //注销信鸽设备
      [OperationManager deleteXGDevice];

      //退出环信
      [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
        //删除所有plist
        [[CommonMethod sharedCommonMethod] deleteAllPlist:^(BOOL isSuccess) {
          if (isSuccess) {
            dispatch_async(dispatch_get_main_queue(), ^{
              hud.hidden = YES;
              //刷新页面
              [self initData];
              [[CommonMethod sharedCommonMethod] showToastInCenter:self.view withMessage:@"退出登录成功"];
            });
          }
        }];
      } onQueue:nil];
    }
  }];
}

//判断申请状态
- (void)judgeApplyStatus {
  [ApplyStatusModel queryApplyStatusWithCompletion:^(ApplyStatusModel *applyStatusModel) {
    if (applyStatusModel) {
      CheckStatusViewController *vc = [[CheckStatusViewController alloc] init];
      vc.statusModel = applyStatusModel;
      vc.hidesBottomBarWhenPushed = YES;
      [self.navigationController pushViewController:vc animated:YES];
    } else {
      BecomeExpertViewController *vc = [[BecomeExpertViewController alloc] init];
      vc.hidesBottomBarWhenPushed = YES;
      [self.navigationController pushViewController:vc animated:YES];
      //NSError *error = [ApplyStatusModel getLastError];
      //[[CommonMethod sharedCommonMethod] showAlertMessage:error.domain];
    }
  }];
}

@end
